<template>
  <div>
    <PageWrapper :contentFullHeight="true">
      <Row :gutter="24">
        <Col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
          <Tabs v-model:activeKey="activeKey" style="background-color: white">
            <TabPane key="1" :tab="t('routes.demo.documentWorkPlace.directory')">
              <div class="tree-container">
                <BasicTree
                  :treeData="partData"
                  :toolbar="true"
                  :search="true"
                  @select="selectPart"
                  :beforeRightClick="rightClick"
                />
              </div>
            </TabPane>
          </Tabs>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="20" :xl="20" style="background-color: white">
          <Row>
            <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <InputSearch
                style="width: 600px; margin-top: 10px"
                v-model:value="searchInfoList.searchStr"
                placeholder="请输入关键字"
                enter-button
                allowClear
                @search="onSearch"
              >
                <template #addonBefore>
                  <Select v-model:value="searchInfoList.flag" style="width: 120px">
                    <SelectOption value="0">模糊搜索</SelectOption>
                    <SelectOption value="1">精确搜索</SelectOption>
                  </Select>
                </template>
                <template #addonAfter>
                  <a-button
                    type="dashed"
                    v-if="searchInfoList.flag === '1'"
                    @click="changeExactModal"
                    >选择</a-button
                  >
                </template>
              </InputSearch>
            </Col>
          </Row>
          <Row>
            <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <BasicTable
                @register="registerTable"
                :searchInfo="searchInfoList"
                :rowSelection="{
                  type: 'checkbox',
                  selectedRowKeys: checkedKeys,
                  onChange: onSelectChange,
                }"
              >
                <!-- 表格顶部左侧区域 -->
                <template #tableTitle>
                  <Alert type="info" show-icon>
                    <template #message>
                      <template v-if="checkedKeys.length > 0">
                        <span
                          >{{ t('common.selected') }}
                          <a @click="getBatchData">{{ checkedKeys.length }}</a>
                          {{ t('common.records') }}</span
                        >
                        <a-button type="link" @click="checkedKeys = []" size="small">{{
                          t('common.clear')
                        }}</a-button>
                      </template>
                      <template v-else>
                        <span>{{ t('common.noSelected') }}</span>
                      </template>
                    </template>
                  </Alert>
                </template>
                <!-- 表格顶部右侧区域 -->
                <template #toolbar>
                  <a-button type="primary" @click="CreatePart" preIcon="ion:plus">
                    {{ t('common.create') }}
                  </a-button>
                  <a-button
                    type="primary"
                    @click="handleContrast"
                    preIcon="ion:md-git-compare"
                    :disabled="checkedKeys.length != 2"
                  >
                    {{ t('routes.demo.partManager.structureComparison') }}
                  </a-button>
                </template>
                <!-- 缩略图 -->
                <template #partUrl="{ record }">
                  <Image :src="record.partUrl" :width="20" :height="20" />
                </template>
                <!-- 代号 -->
                <template #name="{ text: name, record }">
                  <Tooltip :title="name">
                    <a @click="getPartDetail(record)">{{ name }}</a
                    ><Icon icon="ion:ios-copy-outline" color="#7a7374" @click="handleCopy(name)" />
                  </Tooltip>
                </template>
                <!-- 状态 -->
                <template #state="{ text: state, record }">
                  <!-- 零件状态 -->
                  <span v-if="record.fileorpart === '1'">
                    <Tag :color="proxy.$filters.getStatusTag(state)">{{
                      proxy.$filters.filterPartStatus(state)
                    }}</Tag>
                  </span>
                  <span v-else-if="record.fileorpart === '0'">{{
                    proxy.$filters.filterDocumentStatus(state)
                  }}</span>
                </template>
                <!-- 创建时间 -->
                <template #creattime="{ text: creattime }">
                  <span>
                    {{ proxy.$filters.filterTime(creattime) }}
                  </span>
                </template>
                <!-- 文件/零件 -->
                <template #fileorpart="{ text: fileorpart }">
                  {{
                    fileorpart === '0'
                      ? t('routes.demo.partManager.file')
                      : t('routes.demo.partManager.part')
                  }}
                </template>
                <!-- 是否为关联文件 -->
                <template #isshortcut="{ text: isshortcut }">
                  {{ isshortcut === '0' ? t('common.no') : t('common.yes') }}
                </template>
                <!-- 操作 -->
                <template #action="{ record }">
                  <TableAction
                    :actions="[
                      // 零件
                      {
                        icon: 'ion:ios-download-outline',
                        tooltip: t('routes.demo.partManager.checkInPart'),
                        popConfirm: {
                          title: t('routes.demo.partManager.directCheckIn'),
                          placement: 'top',
                          confirm: checkInPart.bind(null, record),
                          cancel: unCheckInPart.bind(null, record),
                          okText: t('common.yes'),
                          cancelText: t('common.no'),
                        },
                        ifShow:
                          record.fileorpart === '1' &&
                          record.state === '2' &&
                          record.prdpower?.some((item) => item.permissionNames == '检入对象'),
                      },
                      {
                        icon: 'ion:ios-upload-outline',
                        tooltip: t('routes.demo.partManager.checkOutPart'),
                        popConfirm: {
                          title: t('routes.demo.partManager.directCheckOut'),
                          placement: 'top',
                          confirm: checkOutPart.bind(null, record),
                          cancel: unCheckOutPart.bind(null, record),
                          okText: t('common.yes'),
                          cancelText: t('common.no'),
                        },
                        ifShow:
                          record.fileorpart === '1' &&
                          record.state === '1' &&
                          record.prdpower?.some((item) => item.permissionNames == '检出对象'),
                      },
                      {
                        icon: 'ion:ios-redo-outline',
                        tooltip: t('routes.demo.partManager.revokePart'),
                        popConfirm: {
                          title: t('routes.demo.partManager.revokePartTip'),
                          placement: 'top',
                          confirm: revokePart.bind(null, record),
                        },
                        ifShow:
                          record.fileorpart === '1' &&
                          record.state === '2' &&
                          record.prdpower?.some((item) => item.permissionNames == '撤销对象'),
                      },
                      {
                        icon: 'ant-design:delete-outlined',
                        tooltip: t('routes.demo.partManager.deletePart'),
                        color: 'error',
                        popConfirm: {
                          title: t('common.confirmDelete'),
                          confirm: DeletePart.bind(null, record),
                        },
                        ifShow:
                          record.fileorpart === '1' &&
                          record.state === '1' &&
                          record.prdpower?.some((item) => item.permissionNames == '删除对象'),
                      },
                      {
                        icon: 'ion:md-remove-circle-outline',
                        tooltip: t('routes.demo.partManager.scrapParts'),
                        color: 'error',
                        popConfirm: {
                          title: t('routes.demo.partManager.scrapPartsTip'),
                          confirm: abolishPart.bind(null, record),
                        },
                        ifShow:
                          record.fileorpart === '1' &&
                          record.state === '1' &&
                          record.prdpower?.some((item) => item.permissionNames == '废止对象'),
                      },
                    ]"
                    :dropDownActions="[
                      {
                        label: t('routes.demo.partManager.modifyPart'),
                        onClick: EditPart.bind(null, record),
                        ifShow: record.fileorpart === '1',
                      },
                      {
                        label: t('routes.demo.partManager.productStructure'),
                        ifShow: record.fileorpart === '1',
                        onClick: handleStruct.bind(null, record),
                      },
                      {
                        label: t('routes.demo.partManager.uploadThumbnail'),
                        onClick: uploadPartImg.bind(null, record),
                        ifShow: record.fileorpart === '1',
                      },
                      {
                        label: t('routes.demo.partManager.workAssignment'),
                        onClick: handleWorkHandOver.bind(null, record),
                        ifShow: record.fileorpart === '1',
                      },
                      {
                        label: t('routes.demo.partManager.useSituation'),
                        onClick: handleUseSituation.bind(null, record),
                        ifShow: record.fileorpart === '1',
                      },
                      {
                        label: t('routes.demo.partManager.associatedPart'),
                        onClick: handlePartAssignObj.bind(null, record),
                        ifShow: record.fileorpart === '1',
                      },
                      {
                        label: t('routes.demo.partManager.associatedFigureDoc'),
                        onClick: handleDocAssign.bind(null, record),
                        ifShow: record.fileorpart === '1',
                      },
                      {
                        label: t('routes.demo.partManager.versionShow'),
                        onClick: handleVersionShow.bind(null, record),
                        ifShow: record.fileorpart === '1',
                      },
                      {
                        label: t('routes.demo.partManager.relatedProcessInstance'),
                        onClick: handleProcess.bind(null, record),
                        ifShow: record.fileorpart === '1',
                      },
                    ]"
                  />
                </template>
              </BasicTable>
            </Col>
          </Row>
        </Col>
      </Row>

      <!-- 目录新增修改 -->
      <directoryModal @register="registerDireModal" @success="reloadGetDirectoryLevel" />
      <!-- 新增零件选择零件类型 -->
      <createPartTypeModal @register="registerCreatePartTypeModal" @success="reload()" />
      <!-- 零件详情 -->
      <partDetailModal @register="registerPartDetailModal" @success="reload()" />
      <!-- 文件工作指派 -->
      <DocWorkAssign @register="registerDocWorkModal" @success="reload()" />
      <!-- 上传预览图 -->
      <uploadImg @register="registerUploadPartImgModal" @success="reload()" />
      <!-- 结构比较 -->
      <partContrast @register="registerPartContrastModal" />
      <!-- 使用情况 -->
      <UseSituation @register="registerUseSituationModal" />
      <!-- 对象类绑定 -->
      <objBindModal @register="registerObjBindModal" />
      <!-- 目录权限设置 -->
      <permissionModal @register="registerPermissionModal" />
      <!-- 版本展示 -->
      <versionShow @register="registerVersionShow" />
      <!-- 精确弹窗 -->
      <ExactModal @register="registerExactModal" @success="searchExact" />
      <!-- 零件详情 -->
      <partDrawer @register="registerPartDrawer" />
      <initiateFlowCopy @register="registerModalCopy" />
      <!-- 目录工作指派 -->
      <workAssignModal @register="registerDireWorkModal" />
      <!-- 检出流程前的判断 -->
      <chekoutModal @register="registerCheckoutModal" @success="reload()" />
      <!-- 关联零件 -->
      <partManagerModal @register="registerPartManagerModal" @success="assPartSuccess" />
      <!-- 关联图档 -->
      <selectDocModal @register="registerSelectDocModal" @success="assDocSuccess" />
      <!-- 相关流程实例 -->
      <flowDetailModal @register="registerFlowDetailModal" />
    </PageWrapper>
  </div>
</template>

<script lang="ts" setup>
  import { ref, getCurrentInstance, nextTick, provide } from 'vue';
  import { useRouter } from 'vue-router';
  import { PageWrapper } from '/@/components/Page';
  import {
    Row,
    Col,
    Tabs,
    TabPane,
    InputSearch,
    Select,
    SelectOption,
    Image,
    Tag,
    Modal,
    Tooltip,
    Alert,
  } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicTree } from '/@/components/Tree/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getPartColumns } from './tableData';
  import { Icon } from '/@/components/Icon';
  import { useUserStore } from '/@/store/modules/user';

  import {
    getDirectoryLevel,
    getPrdFolder,
    deletePrdFolder,
    getWorkAssignList,
    ReversesActivatePower,
    PasteResourceTaskUse,
    ArchiveDirectory,
    GetIsInWorkflow,
    addFolderBindingObject,
  } from '/@/api/demo/document';
  import {
    getPartData,
    PartJustCheckIn,
    RevokePart,
    DeleteAllVersionFile,
    getPartType,
  } from '/@/api/demo/partManager';
  import { getAllPartClass } from '/@/api/demo/system';

  import directoryModal from '../documentManager/directoryModal.vue';
  import createPartTypeModal from './createPartTypeModal.vue';
  import partDetailModal from './partDetailModal.vue';
  import DocWorkAssign from '../documentManager/DocWorkAssign.vue';
  import uploadImg from './uploadImg.vue';
  import partContrast from './partContrast.vue';
  import UseSituation from './UseSituation.vue';
  import objBindModal from '../documentManager/objBindModal.vue';
  import permissionModal from '/@/views/demo/documentManager/components/permissionModal.vue';
  import versionShow from './components/versionShow.vue';
  import ExactModal from '/@/views/components/ExactModal.vue';
  import partDrawer from './components/partDrawer.vue';
  import initiateFlowCopy from '/@/views/demo/workFlow/initiateFlowCopy.vue';
  import workAssignModal from '/@/views/demo/documentManager/workAssignModal.vue';
  import chekoutModal from '/@/views/demo/partManager/chekoutModal.vue';
  import partManagerModal from '/@/views/demo/partManager/components/partManagerModal.vue';
  import selectDocModal from '/@/views/demo/documentManager/components/selectDocModal.vue';
  import flowDetailModal from '/@/views/demo/documentManager/flowDetailModal.vue';

  // 初始化赋值
  const { t } = useI18n();
  const router = useRouter();
  const { createMessage } = useMessage();
  const { proxy }: any = getCurrentInstance();
  const activeKey = ref('1');
  const partSuperId = ref<number>(0);
  const partData = ref<any>([]);
  const searchInfoList = ref<any>({
    folderId: '', // 文件夹id
    searchStr: '', // 查询条件
    flag: '0', // 0 模糊 1 精确
  }); // 模糊查询结果
  // 复制目录id
  const copyDireId = ref<string>('');
  const useCommonStore = useUserStore();
  const checkedKeys = ref<Array<string | number>>([]); // 选中的键
  const selectedRows = ref<any>([]); // 选中的行数据

  // 当选中的行发生改变时调用
  const onSelectChange = (selectedRowKeys: (string | number)[], selectedRowsData: any) => {
    checkedKeys.value = selectedRowKeys; // 更新选中的键
    selectedRows.value = selectedRowsData; // 更新选中的行数据
  };

  const handleReload = () => {
    reload();
  };

  provide('reload', handleReload);

  // 接口
  getDirectoryLevel(partSuperId.value).then((res) => {
    partData.value = res;
  });

  const reloadGetDirectoryLevel = () => {
    getDirectoryLevel(partSuperId.value).then((res) => {
      nextTick(() => {
        partData.value = res;
      });
    });
  };

  // 方法
  const selectPart = (selectedKeys) => {
    searchInfoList.value.folderId = selectedKeys[0];
    reload();
  };

  const rightClick = async (node) => {
    const direSelectData = node.eventKey.split(' ');
    const userSelectData = useCommonStore.userInfo.userId;
    let result = await ReversesActivatePower(direSelectData, [userSelectData]);

    // 解决报错问题，确保 result 至少是一个空数组
    result = result || [];

    const arr = [
      {
        label: t('routes.direPermission.basicFunction'),
        children: [
          {
            label: t('routes.direPermission.createDataDirectory'),
            handler: () => {
              openDireModal(true, { treeKey: node.eventKey, isUpdate: false });
            },
            isShow:
              result.some((item) => item.permissionNames === '新建数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.modifyDataDirectory'),
            handler: () => {
              getPrdFolder(node.eventKey).then((res) => {
                openDireModal(true, { treeKey: node.eventKey, isUpdate: true, res });
              });
            },
            isShow:
              result.some((item) => item.permissionNames === '修改数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.deleteDataDirectory'),
            handler: () => handleDeleteClick(node.eventKey),
            isShow:
              result.some((item) => item.permissionNames === '删除数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.copyDataDirectory'),
            handler: () => {
              copyDireId.value = node.eventKey;
              if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard
                  .writeText(node.eventKey)
                  .then(() => {
                    createMessage.success(t('common.copySuccessText'));
                  })
                  .catch(() => {
                    handleCopyFallback(node.eventKey);
                  });
              } else {
                handleCopyFallback(node.eventKey);
              }
            },
            isShow:
              result.some((item) => item.permissionNames === '复制数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.pasteDataDirectory'),
            handler: () => {
              if (copyDireId.value !== '') {
                PasteResourceTaskUse(copyDireId.value, node.eventKey).then(() => {
                  reloadGetDirectoryLevel();
                  copyDireId.value = '';
                  createMessage.success(t('common.pasteSuccessText'));
                });
              } else {
                createMessage.warning(t('common.pasteWarningText'));
              }
            },
            isShow:
              result.some((item) => item.permissionNames === '粘贴数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.archiveDataDirectory'),
            isShow:
              result.some((item) => item.permissionNames === '归档数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
            handler: () => {
              ArchiveDirectory(node.eventKey).then((res) => {
                if (res) {
                  createMessage.success('归档成功');
                }
              });
            },
          },
        ],
        isShow: true,
      },
      {
        label: t('routes.direPermission.WorkAssignment'),
        handler: () => {
          getWorkAssignList(node.eventKey, '2').then((res) => {
            openDireWorkModal(true, res);
          });
        },
        isShow:
          result.some((item) => item.permissionNames === '工作指派目录') ||
          useCommonStore.userInfo.userId === 'sa',
      },
      {
        label: t('routes.demo.documentWorkPlace.set'),
        children: [
          {
            label: t('routes.demo.documentWorkPlace.permission'),
            handler: () => {
              openDirePermissionModal(true, { treeKey: node.eventKey });
            },
            isShow:
              result.some((item) => item.permissionNames === '设置权限') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.demo.documentWorkPlace.objectClassBind'),
            handler: () => {
              openObjBindModal(true, { treeKey: node.eventKey, type: '零件' });
            },
            isShow:
              result.some((item) => item.permissionNames === '设置对象类绑定') ||
              useCommonStore.userInfo.userId === 'sa',
          },
        ],
        isShow: true,
      },
    ];
    return arr;
  };

  // 删除目录
  const handleDeleteClick = (eventKey: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '删除后无法恢复，确定要删除吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deletePrdFolder(eventKey);
          reloadGetDirectoryLevel();
          createMessage.success('删除成功');
        } catch (error) {
          createMessage.error('删除失败');
        }
      },
    });
  };

  // 新建零件
  const CreatePart = async () => {
    if (searchInfoList.value.folderId === '') {
      createMessage.warning(t('routes.demo.partManagerSettings.directoryPlaceholder'));
    } else {
      const res = await getPartType(searchInfoList.value.folderId);
      openCreatePartTypeModal(true, {
        FolderId: searchInfoList.value.folderId,
        FolderList: res.listPartType,
      });
    }
  };
  // 直接检入零件
  const checkInPart = async (record: Recordable) => {
    if (
      record.prdpower.some((item) => item.permissionNames == '直接检入对象') ||
      useCommonStore.userInfo.userId === 'sa'
    ) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.checkOutPerson !== useCommonStore.userInfo?.userId) {
        createMessage.error('只能执行检出人为自己的对象');
      } else if (record.state !== '2') {
        createMessage.error('仅可检入检出的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        PartJustCheckIn(record.id).then(() => {
          reload();
          createMessage.success(t('routes.demo.partManager.checkInPartSuccess'));
        });
      }
    } else {
      createMessage.error('没有权限直接检入');
    }
  };
  // 检入零件
  const unCheckInPart = async (record: Recordable) => {
    if (
      record.prdpower.some((item) => item.permissionNames == '检入对象') ||
      useCommonStore.userInfo.userId === 'sa'
    ) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.checkOutPerson !== useCommonStore.userInfo?.userId) {
        createMessage.error('只能执行检出人为自己的对象');
      } else if (record.state !== '2') {
        createMessage.error('仅可检入检出的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        openModalCopy(true, {
          record: record,
          type: '检入流程',
          selectedFiles: '',
          projectid: '',
          projectName: '',
          taskName: '',
          formId: '',
          state: '零件',
          isUpdate: false,
        });
      }
    } else {
      createMessage.error('没有权限直接检入');
    }
  };

  // 直接检出零件
  const checkOutPart = async (record: Recordable) => {
    if (
      record.prdpower.some(
        (item) => item.permissionNames == '直接检出对象' || useCommonStore.userInfo.userId === 'sa',
      )
    ) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.state !== '1') {
        createMessage.error('仅可检出生效的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        openCheckOutModal(true, { record: record, type: '直接检出' });
      }
    } else {
      createMessage.error('没有权限直接检出');
    }
  };
  // 检出零件
  const unCheckOutPart = async (record: Recordable) => {
    if (
      record.prdpower.some(
        (item) => item.permissionNames == '检出对象' || useCommonStore.userInfo.userId === 'sa',
      )
    ) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.state !== '1') {
        createMessage.error('仅可检出生效的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        openCheckOutModal(true, { record: record, type: '检出零件' });
      }
    } else {
      createMessage.error('没有权限直接检出');
    }
  };

  // 撤销零件
  const revokePart = (record: Recordable) => {
    RevokePart(record.id).then(() => {
      reload();
      createMessage.success(t('common.undoSuccessText'));
    });
  };

  // 删除零件
  const DeletePart = (record: Recordable) => {
    DeleteAllVersionFile(record.id).then(() => {
      reload();
      createMessage.success(t('common.delSuccessText'));
    });
  };

  // 废止零件
  const abolishPart = (record: Recordable) => {
    GetIsInWorkflow(record.oId).then((res) => {
      if (res) {
        openModalCopy(true, {
          record: record,
          type: '废止流程',
          selectedFiles: '',
          projectid: '',
          projectName: '',
          taskName: '',
          formId: '',
          state: '零件',
          isUpdate: false,
        });
      } else {
        createMessage.warning(t('routes.demo.partManager.notFitRevokeCondition'));
      }
    });
  };

  // 零件详情
  const getPartDetail = (record: Recordable) => {
    openPartDrawer(true, {
      isUpdate: true,
      FolderId: searchInfoList.value.folderId,
      partType: record.type,
      currentRecord: record,
    });
  };

  // 复制代号
  const handleCopyFallback = (text) => {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed'; // 避免影响页面布局
    document.body.appendChild(textarea);
    textarea.select();
    try {
      document.execCommand('copy');
      createMessage.success(t('common.copySuccessText'));
    } catch (err) {
      createMessage.error('复制失败！');
    }
    document.body.removeChild(textarea);
  };

  const handleCopy = (name) => {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard
        .writeText(name)
        .then(() => {
          createMessage.success(t('common.copySuccessText'));
        })
        .catch(() => {
          handleCopyFallback(name);
        });
    } else {
      handleCopyFallback(name);
    }
  };

  // 零件工作指派
  const handleWorkHandOver = (record: Recordable) => {
    if (record.state !== '2') {
      createMessage.error(t('routes.demo.documentManager.objectNotCheckout'));
    } else {
      getWorkAssignList(record.id, '0').then((res) => {
        openDocWorkModal(true, { recordData: record, workAssignList: res, isFrom: '零件' });
      });
    }
  };

  // 使用情况
  const handleUseSituation = (record: Recordable) => {
    openUseSituationModal(true, record);
  };

  // 关联零件
  const handlePartAssignObj = (record: Recordable) => {
    openSelectPartModal(true, { isFrom: '零件工作区关联零件', record: record });
  };

  const assPartSuccess = (fromRecord, toRecord) => {
    // fromRecord:关联的零件 toRecord:被关联的零件
    const Association = ref<any>({
      folderid: searchInfoList.value.folderId,
      oid: toRecord.oId,
      doctype: toRecord.type,
      selectedOid: fromRecord.oId,
      selectedDoctype: fromRecord.type,
    });
    addFolderBindingObject(Association.value).then((res) => {
      if (res) {
        reload();
        createMessage.success(t('routes.demo.documentManager.associatedSuccess'));
      }
    });
  };

  // 关联图档
  const handleDocAssign = (record: Recordable) => {
    openSelectDocModal(true, { type: '零件工作区关联图档', record: record });
  };

  const assDocSuccess = (fromRecord, toRecord) => {
    // fromRecord:关联的零件 toRecord:被关联的零件
    const Association = ref<any>({
      folderid: searchInfoList.value.folderId,
      oid: toRecord.oId,
      doctype: toRecord.doctypeid,
      selectedOid: fromRecord.oId,
      selectedDoctype: fromRecord.type,
    });
    addFolderBindingObject(Association.value).then((res) => {
      if (res) {
        reload();
        createMessage.success(t('routes.demo.documentManager.associatedSuccess'));
      }
    });
  };

  // 版本展示
  const handleVersionShow = (record: Recordable) => {
    openVersionShowModal(true, { record: record });
  };

  // 相关流程实例
  const handleProcess = (record: Recordable) => {
    openFlowDetailModal(true, { currentRecord: record });
  };

  // 上传缩略图
  const uploadPartImg = (record: Recordable) => {
    openUploadPartImgModal(true, { record: record });
  };

  // 修改零件
  const EditPart = (record: Recordable) => {
    openPartDetailModal(true, {
      isUpdate: true,
      FolderId: searchInfoList.value.folderId,
      partType: record.type,
      currentRecord: record,
    });
  };

  // 产品结构
  const handleStruct = (record: Recordable) => {
    router.push({ name: '产品结构', params: { id: record.id, version: record.version } });
  };

  // 结构比较
  const handleContrast = (record: Recordable) => {
    if (checkedKeys.value.length > 2 || checkedKeys.value.length < 2) {
      createMessage.error('只能选择两个文件进行对比浏览');
    } else {
      openContrastModal(true, record);
    }
  };

  // 查询
  const onSearch = () => {
    reload();
  };

  const changeExactModal = async () => {
    const res = await getAllPartClass(); //零件类型数据
    const params = res.map((item) => {
      return {
        key: item.partid,
        title: item.partName,
      };
    });
    openExactModal(true, { partClassList: params });
  };

  const searchExact = (data) => {
    const result = data
      .filter((item) => item.value !== '') // 过滤掉 value 为空的对象
      .map((item) => `${item.prop}:${item.value}`) // 组合 prop 和 value
      .join(','); // 用逗号拼接成字符串
    searchInfoList.value.searchStr = result; // 显示
  };

  // 初始化表格
  const [registerTable, { reload, setLoading }] = useTable({
    api: getPartData,
    columns: getPartColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    // 分页配置
    pagination: false,
    canResize: true,
    isTreeTable: false,
    // childrenColumnName: 'sonpfi',
    rowKey: 'oId',
    actionColumn: {
      width: 200,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 目录弹窗
  const [registerDireModal, { openModal: openDireModal }] = useModal();
  // 新增零件选择零件类型
  const [registerCreatePartTypeModal, { openModal: openCreatePartTypeModal }] = useModal();
  // 零件详情
  const [registerPartDetailModal, { openModal: openPartDetailModal }] = useModal();
  // 文档工作指派
  const [registerDocWorkModal, { openModal: openDocWorkModal }] = useModal();
  // 上传预览图
  const [registerUploadPartImgModal, { openModal: openUploadPartImgModal }] = useModal();
  // 结构比较
  const [registerPartContrastModal, { openModal: openContrastModal }] = useModal();
  // 使用情况
  const [registerUseSituationModal, { openModal: openUseSituationModal }] = useModal();
  // 目录权限设置
  const [registerPermissionModal, { openModal: openDirePermissionModal }] = useModal();
  // 对象类绑定设置弹窗
  const [registerObjBindModal, { openModal: openObjBindModal }] = useModal();
  // 版本展示
  const [registerVersionShow, { openModal: openVersionShowModal }] = useModal();
  // 精确查询
  const [registerExactModal, { openModal: openExactModal }] = useModal();
  // 零件详情
  const [registerPartDrawer, { openDrawer: openPartDrawer }] = useDrawer();
  const [registerModalCopy, { openModal: openModalCopy }] = useModal();
  // 目录工作指派
  const [registerDireWorkModal, { openModal: openDireWorkModal }] = useModal();
  // 流程检出前判断
  const [registerCheckoutModal, { openModal: openCheckOutModal }] = useModal();
  // 关联零件
  const [registerPartManagerModal, { openModal: openSelectPartModal }] = useModal();
  // 关联图档
  const [registerSelectDocModal, { openModal: openSelectDocModal }] = useModal();
  // 相关流程实例
  const [registerFlowDetailModal, { openModal: openFlowDetailModal }] = useModal();
</script>

<style lang="less" scope>
  .text-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .tree-container {
    height: 80vh;
    overflow-y: auto;
  }
</style>
